/*
* @Date: 2020/3/31
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
const { app, webContents } = require('electron');
const fs = require('fs');
const path = require('path');
const babel = require('@babel/core');

exports.newFile = (fileName, dirName) => {
  return new Promise((resolve, reject) => {
    fileName = `${fileName}${fileName.indexOf('.') >= 0 ? '' : '.js'}`;
    fs.exists(dirName, (exists) => {
      if (!exists) {
        fs.mkdir(dirName, (err) => {
          if (err) {
            reject(err);
          }

          fs.writeFile(`${dirName}/${fileName}`, '', 'utf8', (err) => {
            if (err) {
              reject(err);
            }
            resolve({
              dir: dirName,
              file: fileName
            });
          });
        });
      } else {
        fs.writeFile(`${dirName}/${fileName}`, '', 'utf8', (err) => {
          if (err) {
            reject(err);
          }
          resolve({
            dir: dirName,
            file: fileName
          });
        });
      }
    });
  })

}

exports.saveFile = (fileName, content) => {
  return new Promise((resolve, reject) => {
    fs.writeFile(fileName, content, 'utf8', (err) => {
      if (err) {
        reject(err);
      }
      resolve(fileName);
    });
  });
}

/**
 * 编译指定的文件
 * @param fileName
 */
exports.compileFile = (fileName, content) => {
  return new Promise((resolve, reject) => {
    const moduleFileName = fileName.substr(0, fileName.lastIndexOf('.'));
    const module = moduleFileName.substr(moduleFileName.lastIndexOf('/') + 1, moduleFileName.length);
    content = content.replace(/export\s+function\s+([a-zA-Z0-9]+)\s*\(/g, `window.${module}.\$1 = function (`);
    babel.transform(`window.${module} = {};\n${content}`, {
      presets: [
        "@babel/preset-react", "@babel/preset-env"
      ],
      plugins: [
        //'transform-es2015-modules-umd',
        [
          "@babel/plugin-proposal-decorators",
          {
            "legacy": true
          }
        ]
      ]
    }, (err, res) => {
      if (err) {
        reject(err);
      } else {
        fs.writeFile(fileName, res.code, 'utf8', (err) => {
          if (err) {
            reject(err);
          }
          resolve(fileName);
        });
      }
    });
  });
}

exports.runFile = (fileName) => {
  return new Promise((resolve, reject) => {
    if (app.mainWin) {
      const js = fs.readFileSync(path.join(__dirname, `../${fileName}`)).toString();
      app.mainWin.webContents.executeJavaScript(js)
        .then(res => {
          resolve(res);
        }).catch(err => {
          reject(err);
      })
    }
  })

}

exports.openDirectory = (dirPath) => {
  return new Promise((resolve, reject) => {
    fs.exists(dirPath, (exists) => {
      if (!exists) {
        fs.mkdir(dirPath, (err) => {
          if (err) {
            reject(err);
          }
          const dotEle = `${dirPath}\.ele`;
          fs.mkdir(dotEle, (err) => {
            if (err) {
              reject(err);
            }
            resolve(dirPath);
          })
        });
      } else {
        resolve(dirPath);
      }
    });
  })
}
